package com.space.school.controller;

import com.space.school.services.LoginService;
import com.space.school.services.RegisterService;
import com.space.school.services.impl.LoginServiceImpl;
import com.space.school.services.impl.RegisterServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "registerServlet",value = "/registerServlet")
public class RegisterServlet extends HttpServlet {
    private RegisterService registerService = new RegisterServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        跳转到登录页面req.getRequestDispatcher(页面名称)
        req.getRequestDispatcher("register.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        设定取出值的编码格式
        req.setCharacterEncoding("UTF-8");
//         req.getParameter  获取参数  Parameter
        String username = req.getParameter("userName");
        String password = req.getParameter("passWord");
//        判断当以存在账户时,
//        返回 你的账户已存在,请登录
        boolean registerFlag=registerService.Isregister(username);
        if(registerFlag){
            req.getSession().setAttribute("register_msg","你的账户已存在,请登录");
            //            跳转到登录页
            req.getRequestDispatcher("register.jsp").forward(req,resp);
        }else {
//            密码必须是 6位大写,小写,数字都必须有 如果不满足,你的密码设置太简单了,请重新注册
            boolean difficultyFlag=registerService.difficultyPassword(password);
            if(difficultyFlag){
                //      账户,密码
                boolean flag=registerService.register(username,password);
                if(flag){
//            跳转到系统主页面
                    req.getRequestDispatcher("index.jsp").forward(req,resp);
                }else {
//            跳转到登录页
                    req.getSession().setAttribute("register_msg","注册失败");
                    //            跳转到登录页
                    req.getRequestDispatcher("register.jsp").forward(req,resp);
                }
            }else {
                //            跳转到登录页
                req.getSession().setAttribute("register_msg","你的密码设置太简单了,请重新注册");
                //            跳转到登录页
                req.getRequestDispatcher("register.jsp").forward(req,resp);
            }
        }
    }
}
